package com.itheima.tlias.aop;

import com.itheima.tlias.dto.LoginDto;
import com.itheima.tlias.entity.EmpLoginLog;
import com.itheima.tlias.mapper.EmpLoginLogMapper;
import com.itheima.tlias.vo.LoginVo;
import com.itheima.tlias.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Aspect //当前类为切面类
@Slf4j
/*@Order(Ordered.HIGHEST_PRECEDENCE)//指定执行顺序，值越小，执行顺序越靠前*/
public class LoginLogAspect {


    @Autowired
    EmpLoginLogMapper logMapper;

    //环绕通知
    @Around("execution(* com.itheima.tlias.controller.LoginController.login(..))")
    public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {


        Object[] methodParams = pjp.getArgs();
        String username = "";
        String password = "";
        for (Object methodParam : methodParams) {
            if (methodParam instanceof LoginDto) {
                LoginDto loginDto = (LoginDto) methodParams[0];
                username = loginDto.getUsername();
                password = loginDto.getPassword();
            }
        }
        LocalDateTime now = LocalDateTime.now();
        //记录方法执行开始时间
        Long startTime = System.currentTimeMillis();
        Object result = null;
        Long endTime;
        try {
            //执行原始方法
            result = pjp.proceed();
        } finally {
            endTime = System.currentTimeMillis();
            Result newResult = (Result) result;
            Short code = newResult.getCode().shortValue();
            LoginVo data = (LoginVo) newResult.getData();
            String token = data.getToken();
            Integer id = data.getId();
            EmpLoginLog log = EmpLoginLog.builder()
                    .id(id)
                    .username(username)
                    .password(password)
                    .loginTime(now)
                    .isSuccess(code)
                    .jwt(token)
                    .costTime(endTime - startTime)
                    .build();
            logMapper.insert(log);
        }
        return result;
    }
}

